package com.business_clean.app.uitl

import me.hgj.mvvmhelper.ext.logA
import me.hgj.mvvmhelper.ext.logE
import me.hgj.mvvmhelper.net.interception.logging.util.LogUtils
import java.io.UnsupportedEncodingException
import java.net.URLEncoder
import java.security.MessageDigest
import java.util.*


/**
 * url 签名算法
 *
 * @param url       请求地址
 * @param hkToken app的token
 * @param params    请求参数
 * @return 签名后值
 */
fun encodeSign(url: String, hkToken: String, params: Map<String, String>): String? {
    return encodeSign(url, "szd0djn5yMc8weWi", hkToken, params)
}

/**
 * url 签名算法
 *
 * @param url       请求地址
 * @param hkKey   app的秘钥
 * @param hkToken app的token
 * @param params    请求参数
 * @return 签名后值
 */
fun encodeSign(url: String, xmjzKey: String, xmjzToken: String, params: Map<String, String>): String? {
    var xmjzKey = xmjzKey
    var xmjzToken = xmjzToken
    if (params == null) {
        //throw new NullPointerException("HttpParams must not be null!");
        return null
    }
    if (url == null || "" == url) {
        //throw new NullPointerException("Request Url must not be null!");
        return null
    }
    if (xmjzKey == null) {
        xmjzKey = ""
    }
    if (xmjzToken == null) {
        xmjzToken = ""
    }
    val signParams = HashMap(params)
    signParams["xmjz_url"] = url
    val keys: List<String> = ArrayList(signParams.keys)
    Collections.sort(keys) { o1, o2 -> o1.compareTo(o2) }
    val builder = StringBuilder()
    try {
        for (index in keys.indices) {
            val key = keys[index]
            val value = signParams[key]
            builder.append(",").append(key).append("##").append(URLEncoder.encode(value, "UTF-8"))
        }
    } catch (e: UnsupportedEncodingException) {
        e.printStackTrace()
    }
    if (builder.length == 0) {
        builder.append(",")
    }
    var text = ""
    text = if (builder.toString().contains("*")) {
        builder.toString().replace("[*]".toRegex(), "%2A")
    } else {
        builder.toString()
    }
    com.blankj.utilcode.util.LogUtils.e("加密之前的数据 - ${String.format("token=%s,values=%s", xmjzToken, text.substring(1))}")
    val firstStr: String = toMD5(String.format("token=%s,values=%s", xmjzToken, text.substring(1)))
    return toMD5(String.format("%s,%s", firstStr, xmjzKey))
}

/**
 * 对字符串进行MD5加密，返回32位
 *
 * @param plainText
 * @return
 */
fun toMD5(plainText: String): String {
    try {
        //生成实现指定摘要算法的 MessageDigest 对象。
        val md = MessageDigest.getInstance("MD5")
        //使用指定的字节数组更新摘要。
        md.update(plainText.toByteArray())
        //通过执行诸如填充之类的最终操作完成哈希计算。
        val b = md.digest()
        //生成具体的md5密码到buf数组
        var i: Int
        val buf = StringBuffer("")
        for (offset in b.indices) {
            i = b[offset].toInt()
            if (i < 0) i += 256
            if (i < 16) buf.append("0")
            buf.append(Integer.toHexString(i))
        }
        return buf.toString()
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return ""
}